import env from "../../../../utils/env";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    pageNum: 1,
    // 搜索
    serach_pro: "",
    prosum: null,
    prolist: [],
    showSelect: false,
    bankId: '',
    oriProlist: [],
    loading: true,
    userInfo: null,
    totalPages: 1,
    multiple: 10,
    flag: '',
    isOvervies: '',
    searchLevel: '',
    FilePath: '',
    beginDate: '',
    endDate: ''
  },
  checkDetail (e) {
    wx.navigateTo({
      url: `/sub_zhonghang/module2/page_yxtz/page1/page1?userId=${e.currentTarget.dataset.id}&beginDate=${this.data.beginDate}&endDate=${this.data.endDate}`,
    });
  },
  goOnChange (e) {
    this.setData({
      serach_pro: e.detail,
    });
  },
  openMethod () {
    this.setData({
      showSelect: true,
    });
  },
  hideSelect () {
    this.setData({
      showSelect: false,
    });
  },
  goCopy () {
    let that = this;
    wx.setClipboardData({
      data: "www.baidu.com",
      success (res) {
        that.hideSelect();
        wx.showToast({
          title: "链接已复制",
          icon: "none",
        });
      },
    });
  },
  // 搜索
  serachProChange (e) {
    this.setData({
      prolist: [
        {
          bankId: "",
          bankName: "全部分支行",
        },
      ],
      serach_pro: e.detail,
    });
  },

  goExport () {

  },

  // 搜索
  goSearch () {
    this.setData({
      totalPages: 1,
      pageNum: 0,
    })
    this.getList()
  },
  // 滑动底部加载更多
  scrollBottom () {
    // this.onBottom();
  },
  downPage () {
    this.data.pageNum++
    this.setData({
      pageNum: this.data.pageNum
    })
    this.data.prolist = this.data.oriProlist.slice(this.data.multiple * this.data.pageNum, this.data.multiple * this.data.pageNum + this.data.multiple)
    this.setData({
      prolist: this.data.prolist
    })
    this.goTop()
    // console.log(this.data.prolist, 'this.data.prolist')
  },
  upPage () {
    this.data.pageNum--
    this.setData({
      pageNum: this.data.pageNum
    })
    this.data.prolist = this.data.oriProlist.slice(this.data.multiple * this.data.pageNum, this.data.multiple * this.data.pageNum + this.data.multiple)
    this.setData({
      prolist: this.data.prolist
    })
    this.goTop()
    console.log(this.data.prolist, '上一页this.data.prolist')
  },
  //回到顶部
  goTop: function (e) {  // 一键回到顶部
    if (wx.pageScrollTo) {
      wx.pageScrollTo({
        scrollTop: 0
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法回到顶部，请升级到最新微信版本后重试。'
      })
    }
  },
  getList () {
    this.setData({
      loading: true,
    });
    wx.showLoading({
      title: "加载中",
    });
    let params = {
      beginDate: this.data.beginDate,
      endDate: this.data.endDate
    };
    let url = ''
    if (this.data.bankId == 'single') {
      url = '/boc/getOverview'
    } else {
      url = "/boc/getBocUserStatistics"
      params.bankId = this.data.bankId
      if (this.data.searchLevel) {
        params.searchLevel = this.data.searchLevel
      }
    }
    console.log(params, "params");
    getApp()
      .globalData.request(url, params, "POST")
      .then((res) => {
        setTimeout(function () {
          wx.hideLoading();
        }, 500);
        var rstObj = res;
        console.log(res, "res");
        if (rstObj.data) {
          let prolist = rstObj.data.filter(
            d =>
              d.name &&
              (d.name.indexOf(this.data.serach_pro.toLowerCase()) !== -1 ||
                d.name.indexOf(this.data.serach_pro.toUpperCase()) !== -1)
          );
          this.setData({
            oriProlist: JSON.parse(JSON.stringify(prolist)),
            prolist: JSON.parse(JSON.stringify(prolist)).slice(0, this.data.multiple),
            loading: false,
            totalPages: Math.ceil(prolist.length / this.data.multiple)
          });
          // console.log(rstObj.data, "prolist");
          // console.log(this.data.totalPages, "totalPages");
        }
      });
  },
  async openMethod () {
    const res = await this.download()
    setTimeout(function () {
      wx.hideLoading();
    }, 200);
    this.setData({
      showSelect: true,
    });
  },
  download () {
    wx.showLoading({
      title: "导出中...",
    });
    const _this = this
    const params = {
      bankIds: [_this.data.bankId],
      beginDate: _this.data.beginDate,
      endDate: _this.data.endDate
    }
    if(this.data.isOvervies) {
      params.isOvervies = this.data.isOvervies
    }
    console.log(params, 'params')
    return new Promise(function (resolve, reject) {
      wx.request({
        // url: 'http://192.168.1.200:20100/boc/bocSales/getLevelExcel',
        url: env.baseUrl + '/boc/bocSales/getLevelExcel',
        data: params,
        method: 'POST',
        header: {
          "content-type": "application/json",
          "token": wx.getStorageSync('token')
        },
        responseType: "arraybuffer", //注意这里的responseType
        success: (result) => {
          let fileManager = wx.getFileSystemManager();
          _this.data.FilePath = wx.env.USER_DATA_PATH + "/" + 'zx.xlsx';
          console.log(_this.data.FilePath, 'FilePath')
          fileManager.writeFile({
            data: result.data,
            filePath: _this.data.FilePath,
            encoding: "binary", //编码方式 
            success: res => {
              console.log("下载成功！", result);
              resolve('1111')
              // wx.openDocument({ //我这里成功之后直接打开
              //   filePath: FilePath,
              //   showMenu: true,
              //   fileType: "xls",
              //   success: result => {
              //     this.setData({
              //       loadingHidden: true,
              //     })
              //     console.log("打开文档成功");
              //   },
              //   fail: err => {
              //     this.setData({
              //       loadingHidden: true,
              //     })
              //     console.log("打开文档失败", err);
              //   }
              // });
              // // 分享给好友
              // wx.shareFileMessage(
              //   {
              //     filePath: FilePath,
              //     fileName: '测试.xls',
              //     success (data) {
              //       _this.hideSelect()
              //     },
              //     fail (res) {
              //       wx.showToast({
              //         title: JSON.stringify(res),
              //         icon: "none"
              //       })
              //     }
              //   }
              // )
            },
            fail: res => {
              wx.showToast({
                title: '下载失败!',
                icon: 'none', //默认值是success,就算没有icon这个值，就算有其他值最终也显示success
                duration: 2000, //停留时间
              })
            }
          })
        },
        fail (err) {
          console.log(err)
        }
      })
    })

  },
  async downloadWx () {
    const _this = this
    // const res = await _this.download()
    // console.log(res, '下载最后')
    wx.shareFileMessage(
      {
        filePath: _this.data.FilePath,
        fileName: '营销数据.xlsx',
        success (data) {
          _this.hideSelect()
        },
        fail (res) {
          console.log(res, '分享报错的原因')
          // wx.showToast({
          //   title: JSON.stringify(res),
          //   icon: "none"
          // })
        }
      }
    )
  },
  onBottom () {
    if (this.data.prolist.length >= this.data.prosum) return;
    this.data.pageNum++;
    this.getList();
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad (options) {
    this.setData({
      bankId: options.bankId || '',
      beginDate: options.beginDate || '',
      endDate: options.endDate || '',
      searchLevel: options.searchLevel || '',
      isOvervies: options.isOvervies || '',
      beginDate: options.beginDate || '',
      endDate: options.endDate || ''
    })
    wx.setNavigationBarTitle({
      title: options.bankName, //页面标题为路由参数
    });
    this.getList();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady () { },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow () { },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide () { },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload () { },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh () { },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom () { },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage () { },
});
